package com.example.springstudy.configuration;

import com.example.springstudy.common.ResultCode;
import com.example.springstudy.common.ServiceResult;
import lombok.val;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/*
 * 使用该注解表示开启了全局异常的捕获，我们只需在自定义一个方法使用ExceptionHandler注解
 * 然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。
 * 后面用李哥的
 */
@ControllerAdvice
public class ExceptionConfiguration {

    // 全局异常拦截（拦截项目中的所有异常）
    @ResponseBody
    @ExceptionHandler
    public ServiceResult handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 打印堆栈，以供调试
        System.out.println("全局异常：" + e.getMessage());
        e.printStackTrace();

//        // 不同异常返回不同状态码
        ServiceResult rst = null;

        val resultCode = ResultCode.builder().code(500).message(e.getMessage()).build();
        rst = ServiceResult
                .builder()
                .message(resultCode.getMessage())
                .code(resultCode.getCode())
                .success(false)
                .build();
        // 返回给前端
        return rst;
    }
}
